package com.fjec.base.service.impl;

import com.fjec.base.service.ICommonService;
import com.fjec.common.aliyun.sms.AliyunSmsHelper;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.BizException;
import com.fjec.common.exception.SmsException;
import com.fjec.common.util.BizUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class CommonServiceImpl implements ICommonService {

    @Value("${base.sms.signName}")
    private String signName;

    @Value("${base.sms.regVerifyTempCode}")
    private String regVerifyTempCode;

    @Value("${base.sms.updateInfoTempCode}")
    private String updateInfoTempCode;

    @Resource
    private AliyunSmsHelper aliyunSmsHelper;

    @Override
    public void sendRegVerifyCode(String phoneNum, String code) {
        HashMap<String, String> param = new HashMap<>();
        param.put("code", code);
        this.sendMsg(phoneNum, signName, regVerifyTempCode, param);
    }

    @Override
    public void sendChgUserInfo(String phoneNum, String code) {
        HashMap<String, String> param = new HashMap<>();
        param.put("code", code);
        this.sendMsg(phoneNum, signName, updateInfoTempCode, param);
    }

    @CachePut(value = "c_10", key = "'fjec:sms:verify_code:' + #phoneNum")
    @Override
    public String getVerifyCode(String phoneNum) {
        String code = BizUtil.regVerifyCode();
        return code;
    }

    /**
     * 发送短信
     *
     * @param phoneNum
     * @param signName
     * @param tempCode
     * @param param
     */
    private void sendMsg(String phoneNum, String signName, String tempCode, Map<String, String> param) {
        try {
            Map<String, Object> result = aliyunSmsHelper.sendSms(phoneNum, signName, tempCode, param);
            if (!Objects.equals("OK", MapUtils.getString(result, "Code"))) {
                throw new SmsException(EnumSysCode.ERR_0029.getCode(), MapUtils.getString(result, "Message"));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new SmsException(EnumSysCode.ERR_3012.getCode(), e.getMessage());
        }
    }
}
